package server2;

import constants.Constants;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
    private boolean shutdown = false;
    public static void main(String[] args) {
        new HttpServer().await();
    }

    public void await() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(Constants.PORT, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
        while (!shutdown) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                InputStream input = socket.getInputStream();
                OutputStream output = socket.getOutputStream();
                //创建请求对象
                Request request = new Request(input);
                request.parse();
                //创建相应对象
                Response response = new Response(output);
                response.setRequest(request);

                String uri = request.getUri();
                System.out.println(uri);
                if (uri.startsWith("/servlet/")) {
                    new ServletProcessor().process(request, response);
                } else {
                    new StaticResourceProcessor().process(request, response);
                }
                socket.close();
                shutdown = SHUTDOWN_COMMAND.equals(uri);
            }
            catch (Exception e) {
                e.printStackTrace();
                continue;
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
